package com.dengqi.mymodule.activity.permission;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

public class PremissionFragment extends Fragment {

    private final int PERMISSIONS_REQUEST = 10;
    private String[] mustbeList;
    private PermissionUtils.OnCallBack listener;

    public PremissionFragment() {
        // Required empty public constructor
    }

    public static PremissionFragment newInstance() {
        PremissionFragment fragment = new PremissionFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void request(String[] permissions, boolean isMust, PermissionUtils.OnCallBack listener) {
        if (isMust) {
            request(permissions, permissions, listener);
        } else {
            request(permissions, null, listener);
        }
    }

    /**
     * 包含必须同意的权限返回true
     */
    private boolean isMust(List<String> permissions) {
        if (mustbeList == null) {
            return false;
        }
        for (String permission : mustbeList) {
            if (permissions.contains(permission)) {
                return true;
            }
        }
        return false;
    }

    public void request(String[] permissions, String[] mustbeList, PermissionUtils.OnCallBack listener) {
        this.mustbeList = mustbeList;
        this.listener = listener;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            /**
             * 数组转成可remove的集合的迭代器（iterator）
             */
            List<String> persList = new ArrayList<>();
            for (String s : permissions) {
                persList.add(s);
            }
            /**
             * 循环迭代器 如何授权就删除
             */
            Iterator<String> iterator = persList.iterator();
            while (iterator.hasNext()) {
                String permiss = iterator.next();
                //已经申请就移除
                if (ContextCompat.checkSelfPermission(getActivity(), permiss) == PackageManager.PERMISSION_GRANTED) {
                    iterator.remove();
                    continue;
                }
            }
            //剔除已申请成功的权限（留下未申请，拒绝，禁止的权限）
            if (persList.size() > 0) {
                String[] temp = new String[persList.size()];
                persList.toArray(temp);
                requestPermissions(temp, PERMISSIONS_REQUEST);
            } else {
                grantSuccess();
            }
        } else {
            grantSuccess();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST) {
            //禁止或拒绝列表
            List<String> forbidList = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    forbidList.add(permissions[i]);
                }
            }
            if (forbidList.size() > 0) {
                if (isMust(forbidList)) {
                    //有拒绝/禁止，且有必须的权限
                    grantFailed(forbidList);
                } else {
                    //有拒绝/禁止，但没必须的权限
                    grantSuccess();
                }
            } else {
                //全部通过
                grantSuccess();
            }
        }
    }

    private void grantSuccess() {
        if (listener != null) {
            listener.grantSuccess();
        }
    }


    public void grantFailed(List<String> forbidList) {
        new AlertDialog.Builder(getActivity())
                .setTitle("提示!")
                .setMessage("未获得使用权限,请在应用权限设置中打开权限")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        toAppDetailSettingIntent();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (listener != null) {
                            listener.grantFailed();
                        }
                    }
                }).create().show();
    }

    private void toAppDetailSettingIntent() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
        intent.setData(uri);
        getActivity().startActivity(intent);
        getActivity().finish();
    }


}
